package com.analysis.behaviorlogtracing.plugin

import org.objectweb.asm.AnnotationVisitor
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes
import org.objectweb.asm.commons.AdviceAdapter

class BehaviorLogTracingClassVisitor extends ClassVisitor {

    private Boolean isPx = false
    private String className
    private String superName
    private String[] interfaces

    BehaviorLogTracingClassVisitor(ClassVisitor classVisitor) {
        super(Opcodes.ASM7, classVisitor)
    }

    @Override
    void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
        super.visit(version, access, name, signature, superName, interfaces)
        this.className = name
        this.superName = superName
        this.interfaces = interfaces
    }


    @Override
    MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
        MethodVisitor methodVisitor = cv.visitMethod(access, name, descriptor, signature, exceptions)
        MethodVisitor adviceAdapter = new AdviceAdapter(Opcodes.ASM6, methodVisitor, access, name, descriptor) {
            @Override
            protected void onMethodEnter() {
                if (isPx) {
                    if (BehaviorLogUtil.isExtendsActivity(superName)) {
                        println("onMethodExit 正在处理Activity className:" + className)
                        ASMUtil.insertCommonLog(methodVisitor, className, name)
                    }
                    if (BehaviorLogUtil.isMatchingInterfaces(
                            interfaces, 'android/view/View$OnClickListener'
                    ) && "onClick" == name) {
                        println("onMethodExit 正在处理 OnClick 事件:" + className)
                        ASMUtil.insertClickEvent(mv, className)
                    }
                }
                super.onMethodEnter()
            }

            @Override
            protected void onMethodExit(int i) {

                super.onMethodExit(i)
            }
        }
        return adviceAdapter
    }

    @Override
    AnnotationVisitor visitAnnotation(String descriptor, boolean visible) {
        if (descriptor.equals("Lcom/analysis/demo/PxCustomAnnotation;")) {
            isPx = true
            // 这里可以记录或处理带有该注解的类
            System.out.println("Found a class with MyCustomAnnotation");
        }
        return super.visitAnnotation(descriptor, visible)
    }

    @Override
    void visitEnd() {
        super.visitEnd()
    }
}